package com.caipin.controller;

import com.caipin.domain.excel.StudentInfo;
import com.caipin.domain.table.*;
import com.caipin.domain.web.PageBean;
import com.caipin.domain.web.ResultJson;
import com.caipin.service.CourseManagementService;
import com.caipin.service.StudentManagementService;
import com.caipin.service.TeacherManagementService;
import com.caipin.utils.ImportExcel;
import lombok.experimental.Accessors;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-08-01 16:18
 * @Description: TODO
 */
@RestController
@RequestMapping({"/studentManagement"})
public class StudentManagementController {
    @Autowired
    private StudentManagementService studentManagementService;

    @Autowired
    private TeacherManagementService teacherManagementService;

    @Autowired
    private CourseManagementService courseManagementService;

    @Value("${faceImage.studentPath}")
    private String studentImagePath;

    @Value("${faceImage.physicalPath}")
    private String physicalPath;

    @PostMapping({"/studentImport"})
    public Object studentImport(@RequestParam("student") MultipartFile file, HttpServletRequest request) throws IOException {
        InputStream in = file.getInputStream();
        List<StudentInfo> studentInfoList = new ArrayList<>();
        HSSFWorkbook workbook = new HSSFWorkbook(in);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            HSSFSheet sheet = workbook.getSheetAt(i);
            String grade = sheet.getSheetName();
            for (int j = 1; j < sheet.getLastRowNum(); j++) {
                HSSFRow row = sheet.getRow(j);
                if (row.getCell(0) != null && row.getCell(0).getStringCellValue().length() != 0) {
                    StudentInfo studentInfo = (new StudentInfo()).setName(row.getCell(0).getStringCellValue()).setGender(row.getCell(1).getStringCellValue()).setStudentId(row.getCell(2).getStringCellValue()).setParentPhone(row.getCell(3).getStringCellValue()).setGrade(grade).setClbum(row.getCell(4).getStringCellValue()).setPhone(row.getCell(5).getStringCellValue()).setEmail(row.getCell(6).getStringCellValue());
                    for (int k = 7; k < row.getLastCellNum(); k++) {
                        HSSFCell cell = row.getCell(k);
                        if (cell != null)
                            studentInfo.getCourseNameList().add(cell.getStringCellValue());
                    }
                    studentInfoList.add(studentInfo);
                }
            }
        }
        List<Student> studentList = new ArrayList<>();
        List<StudentCourse> studentCourseList = new ArrayList<>();
        for (StudentInfo studentInfo : studentInfoList) {
            studentList.add((new Student())

                    .setName(studentInfo.getName())
                    .setGender(studentInfo.getGender())
                    .setId(studentInfo.getStudentId())
                    .setParentPhone(studentInfo.getParentPhone())
                    .setGrade(studentInfo.getGrade())
                    .setClbum(studentInfo.getClbum())
                    .setEmail(studentInfo.getEmail())
                    .setPhone(studentInfo.getPhone()));
            for (String s : studentInfo.getCourseNameList()) {
                List<TeacherWork> teacherWorkList = this.teacherManagementService.findTeacherWorkListByCourse(s, studentInfo.getGrade());
                for (TeacherWork teacherWork : teacherWorkList) {
                    List<CourseTable> courseTableList = this.courseManagementService.findCourseTableListByWeekAndSectionsAndGradeAndCourseName(teacherWork
                            .getWeek(), teacherWork.getSections(), teacherWork.getGrade(), teacherWork.getCourseName());
                    if (courseTableList == null || courseTableList.size() <= 0)
                        continue;
                    studentCourseList.add((new StudentCourse())

                            .setStudentId(studentInfo.getStudentId())
                            .setCourseName(s)
                            .setCourseType(")
                                    .setBuilding(teacherWork.getBuilding())
                                    .setClassroom(teacherWork.getClassroom())
                                    .setGrade(((CourseTable)courseTableList.get(0)).getGrade())
                                    .setClbum(((CourseTable)courseTableList.get(0)).getClbum())
                                    .setWeek(((CourseTable)courseTableList.get(0)).getWeek())
                                    .setSections(((CourseTable)courseTableList.get(0)).getSections()));
                }
            }
        }
        this.studentManagementService.importStudentCourseToMysql(studentCourseList);
        int count = this.studentManagementService.importStudentToMysql(studentList);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }

    @GetMapping({"/studentList"})
    public Object studentList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize, @RequestParam(value = "studentId", required = false) String studentId, @RequestParam(value = "studentName", required = false) String studentName, @RequestParam(value = "gender", required = false) String gender, @RequestParam(value = "grade", required = false) String grade, @RequestParam(value = "clbum", required = false) String clbum) {
        PageBean<Student> pageBean = null;
        if (studentId != null) {
            pageBean = this.studentManagementService.findStudentListByStudentId(pageNum, pageSize, studentId);
        } else if (studentName == null && gender == null && grade == null && clbum == null) {
            pageBean = this.studentManagementService.findStudentList(pageNum, pageSize);
        } else {
            pageBean = this.studentManagementService.findStudentList(pageNum, pageSize, studentName, gender, grade, clbum);
        }
        return ResultJson.ok(pageBean);
    }

    @GetMapping({"/getStudent/{studentId}"})
    public Object getStudent(@PathVariable("studentId") String studentId) {
        Student student = this.studentManagementService.findStudentByStudentId(studentId);
        return ResultJson.ok(student);
    }

    @DeleteMapping({"/delStudent/{studentId}"})
    public Object delStudent(@PathVariable("studentId") String studentId) {
        this.studentManagementService.delStudentByStudentId(studentId);
        return ResultJson.ok();
    }

    @DeleteMapping({"/delStudentList"})
    public Object delStudentList(@RequestBody List<String> studentIds) {
        int count = this.studentManagementService.delStudentListByStudentIds(studentIds);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }

    @PostMapping({"/addStudent"})
    public Object addStudent(@RequestBody Student student) {
        this.studentManagementService.addStudent(student);
        return ResultJson.ok();
    }

    @PutMapping({"/modifyStudent"})
    public Object modifyStudent(@RequestBody Student student) {
        this.studentManagementService.updateStudent(student);
        return ResultJson.ok();
    }

    @PostMapping({"/APP/uploadStudentPhoto"})
    public Object uploadStudentPhoto(@RequestParam("studentPhotoImage") MultipartFile file) {
        String filename = file.getOriginalFilename();
        String[] s = filename.split("_");
        String studentId = s[0];
        Student student = this.studentManagementService.findStudentByStudentId(studentId);
        if (student == null)
            return ResultJson.failure(ResultCode.BAD_REQUEST, ");
        try {
            byte[] bytes = file.getBytes();
            FileOutputStream fileOutputStream = FileUtils.openOutputStream(new File(this.physicalPath + this.studentImagePath, filename));
            fileOutputStream.write(bytes);
            fileOutputStream.close();
            String imageBase64 = Base64.getEncoder().encodeToString(bytes);
            this.studentManagementService.saveStudentPhoto(student, this.studentImagePath + "/" + filename, imageBase64);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultJson.ok();
    }

    @GetMapping({"/studentCourseList"})
    public Object studentCourseList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize, @RequestParam(value = "studentId", required = false) String studentId, @RequestParam(value = "courseName", required = false) String courseName, @RequestParam(value = "courseType", required = false) String courseType, @RequestParam(value = "building", required = false) String building, @RequestParam(value = "classroom", required = false) String classroom, @RequestParam(value = "schoolYear", required = false) String schoolYear, @RequestParam(value = "semester", required = false) Integer semester, @RequestParam(value = "grade", required = false) String grade, @RequestParam(value = "clbum", required = false) String clbum, @RequestParam(value = "week", required = false) Integer week, @RequestParam(value = "sections", required = false) Integer sections) {
        PageBean<StudentCourse> pageBean = null;
        if (studentId != null) {
            pageBean = this.studentManagementService.findStudentCourseListByStudentId(pageNum, pageSize, studentId);
        } else if (courseName == null && courseType == null && building == null && classroom == null && schoolYear == null && semester == null && grade == null && clbum == null && week == null && sections == null) {
            pageBean = this.studentManagementService.findStudentCourseList(pageNum, pageSize);
        } else {
            pageBean = this.studentManagementService.findStudentCourseList(pageNum, pageSize, courseName, courseType, building, classroom, schoolYear, semester, grade, clbum, week, sections);
        }
        return ResultJson.ok(pageBean);
    }

    @GetMapping({"/studentCourse/{studentCourseId}"})
    public Object getStudentCourse(@PathVariable("studentCourseId") Long studentCourseId) {
        StudentCourse studentCourse = this.studentManagementService.findStudentCourseByStudentCourseId(studentCourseId);
        return ResultJson.ok(studentCourse);
    }

    @DeleteMapping({"/studentCourse/{studentCourseId}"})
    public Object delStudentCourse(@PathVariable("studentCourseId") Long studentCourseId) {
        this.studentManagementService.delStudentCourseByStudentCourseId(studentCourseId);
        return ResultJson.ok();
    }

    @PostMapping({"/studentCourse"})
    public Object addStudentCourse(@RequestBody StudentCourse studentCourse) {
        this.studentManagementService.addStudentCourse(studentCourse);
        return ResultJson.ok();
    }

    @PutMapping({"/studentCourse"})
    public Object modifyStudentCourse(@RequestBody StudentCourse studentCourse) {
        this.studentManagementService.updateStudentCourse(studentCourse);
        return ResultJson.ok();
    }

    @DeleteMapping({"/delStudentCourseList"})
    public Object delStudentCourseList(@RequestBody List<Long> studentCourseIds) {
        int count = this.studentManagementService.delStudentCourseListByStudentCourseIds(studentCourseIds);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }
}
